package com.example.back.Controller;

import com.example.back.Annotation.UserLoginToken;
import com.example.back.Entity.BigSale;
import com.example.back.Repository.BigSaleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

/**
 * 甩卖模块，负责和Redis适配
 */
@RestController
@RequestMapping("bigSale")
public class BigSaleController {
    @Autowired
    private BigSaleRepository bigSaleRepository;
    @UserLoginToken
    @PostMapping("")
    public boolean addNewBigSale(@RequestBody BigSale bigSale){
        try{
            bigSaleRepository.save(bigSale);
        }catch (Exception e){
            return false;
        }
        return true;
    }
    @UserLoginToken
    @GetMapping("/list/{orderName}/{asc}/{page}")
    public Page<BigSale> findAllBigSale(@PathVariable("orderName") String orderName,
                                        @PathVariable("page") int page,
                                        @PathVariable("asc") int asc){
        Pageable pageable;
        if(asc==1){
            pageable=PageRequest.of(page-1,10, Sort.Direction.ASC,orderName);
        }else {
            pageable=PageRequest.of(page-1,10, Sort.Direction.DESC,orderName);
        }
        return bigSaleRepository.findAll(pageable);
    }
    @UserLoginToken
    @GetMapping("/BSN/{BSN}/{orderName}/{asc}/{page}")
    public Page<BigSale> findAllByBSN(@PathVariable("BSN") String BSN,
                                      @PathVariable("orderName") String orderName,
                                      @PathVariable("page") int page,
                                      @PathVariable("asc") int asc){
        Pageable pageable;
        if(asc==1){
            pageable=PageRequest.of(page-1,10, Sort.Direction.ASC,orderName);
        }else {
            pageable=PageRequest.of(page-1,10, Sort.Direction.DESC,orderName);
        }
        return bigSaleRepository.findAllByBigSaleNameContains(pageable,BSN);
    }
}
